<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020/9/17 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace console\controllers;

use Yii;
use common\models\RegisterForm;
use common\models\User;
use yii\console\Controller;
use yii\console\ExitCode;

class InitController extends Controller
{
    public function actionConfig()
    {
        echo "begin init Config tb!\n";
        Yii::$app->config->initConfigTable();
        echo "Ok init Config tb!\n";
        return ExitCode::OK;
    }

    /**
     * @return int
     * @throws \yii\base\Exception
     */
    public function actionCreateAdmin()
    {
        echo "create an administrator ...\n"; // comment 提示当前操作
        $id = (int) $this->prompt('Administrator login uid:'); // 接收用户id
        $mobile = $this->prompt('Administrator login mobile:'); // 接收用户手机号
        $pwd = $this->prompt('Administrator login password:'); // 接收登录密码
        $register = new RegisterForm();
        $register->mobile = trim($mobile);
        $register->password = trim($pwd);
        $register->group = 1;//设为管理员组
        if ($register->register($id)) {
            // 绑定超级管理员
            $auth = Yii::$app->getAuthManager();
            $role = $auth->getRole('administrator');
            $auth->assign($role, $id);
            echo "create admin success\n";
        } else {
            echo "create admin error\n";
        }
        return ExitCode::OK;
    }

    /**
     * 设置用户为管理员
     * @return int
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionSetAdmin()
    {
        echo "set an administrator ...\n"; // comment 提示当前操作
        $uid = (int) $this->prompt('Administrator user id:'); // 接收用户id
        $gid = $this->prompt('Administrator group id:'); // 接收管理员组id
        if ($user = User::findOne($uid)) {
            $user->group_id = (int) $gid;
            $user->update(false, ['group_id']);
            echo "setting success\n";
        }
        return ExitCode::OK;
    }
}